
import Pagination from '@/components/pagination';
import mixin from '@/service/mixin';
import {keyMap} from '@/config';
import SelectAppList from '@/components/select-app-list';
import SelectKanaList from '@/components/select-kana-list';

export default {
    name: 'loanFailedList',
    components: {
        Pagination,
        SelectAppList,
        SelectKanaList
    },
    mixins: [mixin],
    data() {
        return {
            domain:'',
            form: {
                orderId: '',
                userPhone: '',
                withdrawAccount: '',
                userId: '',
                applyTime: '',
                loanCmplTime: '',
                thirdPartyOrderId: '',
                product: '',
                appName: '',
                kana:'',
                whiteProductName:''
            },
            rules: {
                orderId: [],
                userPhone: [],
                withdrawAccount: [],
                userId: [],
                applyTime: [],
                loanCmplTime: [],
                thirdPartyOrderId: [],
            },
            showRefuseDialog: false,
            showBatchRefuseButton: false,
            refuseForm: {
                reason: '',
                label: '',
                orderId: ''
            },
            selectedIdList: {
                ids: [],
                orderIds: [],
                list: [],
            },
            keyMap,
            showEditName: false,
            nameForm: {
                firstName: '',
                middleName: '',
                lastName: '',
                orderId: '',
                showErrorMsg: false,
            },
            nameFormRules: {
                lastName: [
                    {required: true, message: this.$t('verify.plsInput'), trigger: 'blur'},
                    {pattern: /^[^0-9]+$/, message: this.$t('verify.plsInputRightX',{x: 'last name'})},
                ],
                firstName: [
                    {required: true, message: this.$t('verify.plsInput'), trigger: 'blur'},
                    {pattern: /^[^0-9]+$/, message: this.$t('verify.plsInputRightX',{x: 'first name'})},
                ],
                middleName: [
                    // {required: true, message: this.$t('verify.plsInput'), trigger: 'blur'},
                    {pattern: /^[^0-9]+$/, message: this.$t('verify.plsInputRightX',{x: 'middle name'})},
                ],
            }
        };
    },
    methods: {
        getTableData(page = this.page) {
            const params = this.fillParams(page);
            this.$api.finance.loan.failureList(params).then(res => {
                const {status, data, error} = res;
                if ('1' === status && '00000000' === error && data) {
                    this.tableData = data.resultData;
                    this.setPage(data.page, this.page);
                }
            });
        },
        search() {
            this.page.currentPage = 1;
            this.getTableData();
        },
        exportExcel() {
            const params = this.fillParams();
            const user = this.$storage.get('user');
            const language = this.$storage.getLocal('language');
            params.language = language;
            params.token = user.token;
            const {$apiConf} = this;
            const url = this.$urlUtil.fillParams(params, $apiConf.baseUrl + $apiConf.urlType.finance.loan.failureExcel, ['page']);
            this.$openNewBlank(url);
        },
        fillParams(page = this.page) {
            const form = this.form;
            const params = {
                orderId: '',
                userPhone: '',
                withdrawAccount: '',
                userId: '',
                applyTimeStart: '',
                applyTimeEnd: '',
                loanTimeStart: '',
                loanTimeEnd: '',
                thirdPartyOrderId: '',
                product: '',
                appName: '',
                kana:'',
                whiteProductName:'',
                page: {
                    pageNo: page.currentPage,
                    pageSize: this.page.pageSize
                }
            };
            Object.keys(form).forEach(key => {
                if (typeof form[key] === 'string' && form[key]) {
                    form[key] = form[key].trim();
                    params[key] = form[key];
                }
            });
            if (form.applyTime) {
                params.applyTimeStart = form.applyTime[0];
                params.applyTimeEnd = form.applyTime[1];
            }
            if (form.loanCmplTime) {
                params.loanTimeStart = form.loanCmplTime[0];
                params.loanTimeEnd = form.loanCmplTime[1];
            }
            return params;
        },
        // 拒绝放款弹框
        showRefuse(row) {
            this.refuseForm.label = this.$t('common.orderId') + '：' + row.orderId;
            this.refuseForm.reason = '';
            this.refuseForm.orderId = row.orderId;
            this.showRefuseDialog = true;
            this.showBatchRefuseButton = false;
        },
        refuse() {
            const form = this.refuseForm;
            form.reason = form.reason.trim();
            if (form.reason === '') {
                this.$message.warning(this.$tc('verify.plsInputRefuseReason'));
                return false;
            }
            const params = {
                orderId: form.orderId,
                remark: form.reason
            };
            this.$api.finance.loan.refuseToLendMoney(params).then(res => {
                const {status, msg, error} = res;
                if ('1' === status && '00000000' === error) {
                    this.showRefuseDialog = false;
                    this.$message.success(msg || this.$tc('common.successfulOperation'));
                    this.getTableData();
                }
            });
        },
        // 放款通过
        showPass(row) {
            this.$confirm(this.$t('common.orderId') + '：' + row.orderId, this.$t('common.confirmLoan') + '？').then(value => {
                if (value === 'confirm') {
                    const params = {
                        id: row.id,
                    };
                    this.$api.finance.loan.agreeToLendMoney(params).then(res => {
                        const {status, msg, error} = res;
                        if ('1' === status && '00000000' === error) {
                            this.$message.success(msg || this.$tc('common.successfulOperation'));
                            this.getTableData();
                        }
                    });
                }
            }).catch(() => {
                //
            });
        },
        // 列表多选处理
        handleTableSelect(val) {
            this.selectedIdList.ids = [];
            this.selectedIdList.orderIds = [];
            this.selectedIdList.list = [];
            val.forEach(item => {
                this.selectedIdList.ids.push(item.id);
                this.selectedIdList.orderIds.push(item.orderId);
                this.selectedIdList.list.push(item);
            });
        },
        // 批量同意放款
        batchPass() {
            let arr = this.selectedIdList.list.filter( item => {
                return item.modifyAcountStatus === 1;
            });
            if(arr && arr.length > 0) {
                this.$message.warning(this.$tc('common.hasChangeOrderReChoose'));
                return
            }
            this.$confirm(this.$tc('finance.forXOrderLoan', 1, { x: this.selectedIdList.ids.length }), this.$tc('common.confirmLoan') + '？').then(value => {
                if (value === 'confirm') {
                    const params = {
                        idStrs: this.selectedIdList.ids.join(','),
                    };
                    this.$api.finance.loan.batchAgreeToLendMoney(params).then(res => {
                        const {status, msg, error} = res;
                        if ('1' === status && '00000000' === error) {
                            this.$message.success(msg || this.$tc('common.successfulOperation'));
                            this.getTableData();
                        }
                    });
                }
            }).catch(() => {
                //
            });
        },
        // 批量拒绝
        batchRefuse() {
            const form = this.refuseForm;
            form.reason = form.reason.trim();
            if (form.reason === '') {
                this.$message.warning(this.$tc('verify.plsInputRefuseReason'));
                return false;
            }
            const params = {
                orderIdStrs: this.selectedIdList.orderIds.join(','),
                remark: form.reason
            };
            this.$api.finance.loan.batchRefuseToLendMoney(params).then(res => {
                const {status, msg, error} = res;
                if ('1' === status && '00000000' === error) {
                    this.showRefuseDialog = false;
                    this.$message.success(msg || this.$tc('common.successfulOperation'));
                    this.getTableData();
                }
            });
        },
        // 显示批量拒绝提交按钮
        showBatchRefuse() {
            this.refuseForm.label = this.$t('finance.batchRefuseXOrder', {x: this.selectedIdList.ids.length});
            this.refuseForm.reason = '';
            this.showRefuseDialog = true;
            this.showBatchRefuseButton = true;
        },
        // 处理行数据
        handleRowKey(row) {
            // console.log(row);
            return row.id;
        },
        // 修改
        changeSubmit(row) {
            this.$confirm(this.$tc('common.isConfirmChange'), '', {
                confirmButtonText: this.$t('common.confirm'),
                cancelButtonText: this.$t('common.cancel'),
                type: 'warning'
            }).then(() => {
                const params = {
                    id: row.id
                };
                this.$api.finance.loan.agreeToModify(params).then((res) => {
                    const {status, error, msg} = res;
                    if ('1' === status && error === '00000000') {
                        this.getTableData();
                        this.$message.success(this.$tc('common.successfulOperation'));
                    }
                });
            }).catch(() => {
            });
        },
        // 批量线下放款
        batchOfflineLoan() {
            const channels = keyMap.offlineLoanChannelName;
            const channelsValue = keyMap.offlineLoanChannelValue;
            const list = this.selectedIdList.list.filter(item => {
                if (channelsValue.includes(+item.withdrawChannel)) return item;
            });
            if (list.length !== this.selectedIdList.list.length) {
                this.$message.error(this.$tc('finance.plsSelectDesignatedChannelsOrders', 1, { way: channels.join(',') })); // 只能选择放款方式为Bank、GCash、Coins的订单
                return ;
            }
            const modifyList = this.selectedIdList.list.filter(item => item.modifyAcountStatus === 1);
            if (modifyList.length > 0) {
                this.$message.error(this.$tc('finance.failListOfflineLoanTips')); // 取款渠道处于【修改中】的订单不可转为线下放款
                return;
            }
            const ids = this.selectedIdList.ids;
            // 确认批量处理${ids.length}条订单？
            this.$confirm(this.$tc('common.confirmBatchHandleTips', 1, { count: ids.length }), this.$tc('common.tips')).then(() => {
                const params = {
                    idList: ids,
                    type: '2', // type:触发类型，1-待放款列表，2-放款失败列表, 3-取消线下放款，进入待放款
                };
                this.$api.finance.loan.updateOfflineStatus(params).then(res => {
                    const { status } = res;
                    if ('1' === status) {
                        this.$message.success(this.$tc('common.successfulOperation')); // '操作成功'
                        this.getTableData();
                    }
                });
            }).catch(() => {});
        },
        // 编辑姓名
        editName(row) {
            const { orderId, userId } = row;
            // 查询具体的用户姓名
            this.$api.customer.getBaseByUserId({ userId }).then(res=> {
                const { status, data, error } = res;
                if ('1' === status && '00000000' === error && data) {
                    const { firstName, middleName, lastName } = data;
                    this.nameForm.firstName = firstName || '';
                    this.nameForm.middleName = middleName || '';
                    this.nameForm.lastName = lastName || '';
                    this.nameForm.orderId = orderId;
                    this.showEditName = true;
                }
            });
        },
        handleEditName() {

            const { firstName, middleName, lastName, orderId } = this.nameForm;
            if (!firstName && !middleName && !lastName) {
                this.nameForm.showErrorMsg = true;
                return;
            }
            const nameForm = this.$refs.nameForm;
            nameForm.validate(val => {
                if (val) {
                    const params = { firstName, middleName, lastName, orderId };
                    this.$api.finance.loan.renamePayFail(params).then(res => {
                        const { status, error, msg } = res;
                        if ('1' === status && '00000000' === error) {
                            this.$message.success(this.$tc('common.modifySuccess'));
                            this.showEditName = false;
                            this.getTableData();
                        } else {
                            this.$message.error(msg || this.$tc('common.modifyFail')); // 修改失败
                        }
                    });
                }
            });

        },
    },
    created() {
        this.domain = this.$storage.get('user').domain
        this.tableMaxHeight = document.body.clientHeight - 265;
        this.getTableData();
    }
}
